import { Inject } from '@midwayjs/decorator';
import { Provide } from '@midwayjs/decorator';
// import { BaseService } from 'midwayjs-cool-core';

import { InjectEntityModel } from '@midwayjs/orm';
import { Context } from 'egg';
import { Repository } from 'typeorm';
import { loeeBaseService } from '../../../comservice/loeeBaseService';
import { courseSystemEntity } from '../entity/courseSystem';

/**
 * 描述
 */
@Provide()
export class courseSystemService extends loeeBaseService {
  @InjectEntityModel(courseSystemEntity)
  courseSystemEntity: Repository<courseSystemEntity>;

  @Inject()
  ctx:Context

  /**
   * 重写分页查询
   * @param query
   */
   async page(query) {
    const { keyWord,course_type} = query;
    console.log("this is query------------------------------",query);
    // query.order = 'sort'
    // query.sort = 'asc'
    // const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
    //   this.ctx.admin.userId
    // ); // 部门权限
    const sql = `
        (SELECT
            a.id,a.phase_name,a.phase_course_introduce,a.sort,a.course_type,a.note,a.createTime,a.updateTime,a.isDelete,
            GROUP_CONCAT(b.id,"-",IFNULL(b.phase_sort,""),"、",IFNULL(b.section_theme,""),"：",IFNULL(b.learning_goals,"") order by b.phase_sort asc) AS courseNames
        FROM
            course_system a
            LEFT JOIN course_source b ON a.id = b.phase_name
        WHERE a.isDelete = false and b.isDelete = false
        ${this.setSql(course_type, 'and a.course_type = ?', [course_type])}
        ${this.setSql(keyWord, 'and (a.phase_name LIKE ? or a.phase_course_introduce LIKE ? or b.section_theme LIKE ? or b.learning_goals LIKE ?)', [
          `%${keyWord}%`,
          `%${keyWord}%`,
          `%${keyWord}%`,
          `%${keyWord}%`,
        ])}
        GROUP BY a.id
        order by a.course_type asc,a.sort asc)
        union all
        (
          select a.id,a.phase_name,a.phase_course_introduce,a.sort,a.course_type,a.note,a.createTime,a.updateTime,a.isDelete,'无' as courseNames from course_system a
          LEFT JOIN course_source b ON a.id = b.phase_name
          where a.isDelete = false and a.id not in (
            select phase_name as id from course_source where isDelete = false and phase_name is not null
          ) 
          ${this.setSql(course_type, 'and a.course_type = ?', [course_type])}
  
          ${this.setSql(keyWord, 'and (a.phase_name LIKE ? or a.phase_course_introduce LIKE ? or b.section_theme LIKE ? or b.learning_goals LIKE ?)', [
            `%${keyWord}%`,
            `%${keyWord}%`,
            `%${keyWord}%`,
            `%${keyWord}%`,
          ])}
        )
        order by course_type asc,sort asc
        `;
    return this.sqlRenderPage(sql, query, true);
  }
  
  
}
